<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\model\AppConfig;
use app\common\model\MpUser;
use app\common\model\User as UserModel;
use think\Response;

class MpBindLogic
{
    /**
     * bindMp
     * @param array $param
     * @throws
     */
    public function bindMp(array $param)
    {
        // 提取参数
        $code = $param['code'];
        $appId = getAppId();
        $userId = $param['userId'];

        // 剔除code中含有的中文或冒号
        $code = removeChineseCharacters($code);
        $code = str_replace('：', '', $code);
        $code = trim($code);

        // 查询绑定配置
        $config = app(AppConfig::class)->getByIdAndType($appId, 'mp');
        if (!$config) {
            throw new BusinessException('请先配置公众号参数');
        }

        // 初始化活动模型
        $scoreActivity = app(ScoreActivity::class);
        $check = $scoreActivity->check_source($userId, 11);
        if (!$check) {
            throw new BusinessException('您已经绑定公众号');
        }

        // 根据绑定模式执行
        if ($config['user_bind_type'] == 1) {
            $this->bindByFixed($code, $config['user_bind_code']);
        } else {
            $this->bindByDynamic($userId, $code);
        }

        // 赠送积分
        try {
            app(ScoreActivity::class)->initConfig($appId)->send($userId, 11);
        } catch (\Exception $exception) {

        }
    }

    private function bindByFixed($code, $configCode)
    {
        if ($code != $configCode) {
            throw new BusinessException('公众号验证码不正确' . $code);
        }
    }

    private function bindByDynamic($userId, $code)
    {
        // 查询用户信息
        $field = 'openid,mp_openid,email,username';
        $info = app(UserModel::class)->where(['id' => $userId])->field($field)->find();
        if ($info['mp_openid']) {
            throw new BusinessException('您已经绑定公众号');
        }

        // 查询code真实性
        $where = [['openid', '=', $code]];
        $codeInfo = app(MpUser::class)->where($where)->find();
        if (!$codeInfo) {
            throw new BusinessException('公众号验证码不正确');
        }

        // 查询code是否被其他人使用
        $count = app(UserModel::class)->where(['mp_openid' => $code])->count();
        if ($count) {
            throw new BusinessException('公众号验证码已绑定过');
        }

        // 更新数据
        $userData = [
            'mp_openid' => $code,
            'is_agent' => 1,
            'whitelist' => 1,
            'update_time' => time()
        ];
        $isUpdate = app(UserModel::class)->where(['id' => $userId])->save($userData);
        if (!$isUpdate) {
            throw new BusinessException('更新失败');
        }
    }
}